package com.feihong.txgw.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.ui.activity.user.LiuLiangChaXunActivity;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @name txgw_app
 * @class name：com.feihong.txgw.dialog
 * @class describe:  流量查询 验证手机号dialog
 * @author wangziheng
 * @time 2017/7/6 17:17
 * @change
 * @chang time
 * @class describe
 */

public class LiuLiangChaXunVerifyCardDialog extends Dialog implements View.OnClickListener {
    private LiuLiangChaXunActivity mContext;
    private String mUserPhoneNum;
    private EditText mVertifyCode;
    private TextView mQueryCodeBtn;
    private TextView mVertifyBtn;
    private TimeCount mTimeCount;
    private TextView mVertifyUserPhNum;
    private String mIcp_id;

    public LiuLiangChaXunVerifyCardDialog(@NonNull Context context, String phoneNum, String icp_id) {
        super(context, R.style.LiuLiangChaXunVertifyCardStype);
        mContext = (LiuLiangChaXunActivity) context;
        mUserPhoneNum = phoneNum;
        mIcp_id = icp_id;
        initView();
    }

    private void initView() {
        setContentView(R.layout.liuliangchuanxun_dialog_layout);
        mTimeCount = new TimeCount(60000, 1000);
        mVertifyCode = (EditText) findViewById(R.id.llcx_vertify_code_et);
        mQueryCodeBtn = (TextView) findViewById(R.id.llcx_query_vertify_code_tv);
        mVertifyBtn = (TextView) findViewById(R.id.llcx_vertify_code_btn);
        mVertifyUserPhNum = (TextView) findViewById(R.id.llcx_vertify_user_phNum);
        mVertifyUserPhNum.setText(mUserPhoneNum);
        mVertifyBtn.setOnClickListener(this);
        mQueryCodeBtn.setOnClickListener(this);
        // 屏蔽点击空拍dialog消失
        setCanceledOnTouchOutside(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llcx_query_vertify_code_tv:
                if (isFastDoubleClick()) {
                    return;
                }
                mTimeCount.start();
                setCancelable(false);
                mContext.queryPremission();
                queryVertifyCode();
                break;
            case R.id.llcx_vertify_code_btn:
                if (!TextUtils.isEmpty(mVertifyCode.getText().toString())) {
                    vertifyPhoneNum();
                } else {
                    mContext.showSystemToast("验证码不能为空");
                }
                break;
            default:break;
        }
    }

    /**
     * 验证手机号
     */
    private void vertifyPhoneNum() {
        setCancelable(true);
        KeyboardUtils.hideSoftInput(mContext);
        mContext.queryPackageInfo(mIcp_id, mUserPhoneNum, mVertifyCode.getText().toString());
        cancel();
    }

    /**
     * 获取验证码
     */
    private void queryVertifyCode() {
        RetrofitManager.getInstance().sendVertiryCode(mIcp_id,mUserPhoneNum)
        .compose(RxHelper.<String>rxSchedulerHelper())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("200".equals(jsonObject.optString("code"))) {
                        setCancelable(false);
                        mContext.showSystemToast("验证码已发送");
                    } else {
                        mTimeCount.cancel();
                        mTimeCount.onFinish();
                        setCancelable(true);
                        mContext.showSystemToast(jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mContext.showDialog(null, "获取验证码失败");
                    mTimeCount.onFinish();
                    setCancelable(true);
                }
            }

            @Override
            public void onError(Throwable e) {

                mTimeCount.cancel();
                mTimeCount.onFinish();
                setCancelable(true);
                mContext.showDialog(null, "获取验证码失败");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            if(mContext.activityIsDestory()){
                return;
            }
            mQueryCodeBtn.setClickable(false);
            mQueryCodeBtn.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            if(mContext.activityIsDestory()){
                return;
            }
            // TODO Auto-generated method stub
            mQueryCodeBtn.setClickable(true);
            setCancelable(true);
            mQueryCodeBtn.setText("再次获取");
        }
    }

    public void showDialog() {
        show();
        WindowManager windowManager = mContext.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //设置宽度
        lp.width = (int) (display.getWidth());
        getWindow().setAttributes(lp);
    }

    public void setCode(String code){
        mVertifyCode.setText(code);
    }
    /**
     * 防止双点
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 700) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 弹窗取消
     */
    public void cancelDialog(){
        if(mTimeCount != null){
            mTimeCount.cancel();
        }
        cancel();
    }
}
